package com.heima.datasync.service.impl;
import com.heima.common.consatnts.search.SearchConstants;
import com.heima.common.exception.CustException;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EsDataServiceImpl implements EsDataService {
    public static final String ARTICLE_INDEX_NAME = "app_info_article";
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private EsService<SearchArticleVO> esService;
    @Override
    public ResponseResult dataInit() {
        // 0 . 判断索引库是否存在
        boolean isExist = esService.existIndex(SearchConstants.ARTICLE_INDEX_NAME);
        //     如果存在 删除之前的索引库
        if(isExist){
            esService.deleteIndex(SearchConstants.ARTICLE_INDEX_NAME);
        }
        //    创建索引库
        esService.createIndex(SearchConstants.ARTICLE_INDEX_PARAMS,SearchConstants.ARTICLE_INDEX_NAME);
        // 1. 从数据库中查询 文章的数据
        // 1.1  查询当前满足条件的文章总数量  count
        // 1.2  page(页数)   =  count / size  + 1
        // 1.3  for (int i=1     page   )       (page -1 ) * size    size
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        // 2. 使用es的批量处理api 批量插入数据到es
        if (CollectionUtils.isEmpty(allArticles)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据库中没有文章数据");
        }
        List<SearchArticleVO> voList = allArticles.stream()
                .map(this::parseSearchArticleVO)
                .collect(Collectors.toList());
        // 批量保存
        esService.saveBatch(voList,SearchConstants.ARTICLE_INDEX_NAME);
        return ResponseResult.okResult();
    }
    private SearchArticleVO parseSearchArticleVO(ApArticle apArticle){
        SearchArticleVO searchArticleVO = new SearchArticleVO();
        BeanUtils.copyProperties(apArticle, searchArticleVO);
        return searchArticleVO;
    }
}